<template>
	<view>
		<!-- 头部内容 -->
		<view class="head-container">
			<view class="image-container">
				<!-- 左侧图片 -->
				<image :src="headImgSrc" class="head-img" mode="widthFix"></image>
			</view>
			<!-- 体重文字 -->
			<view class="txt-container" v-if="recentDay > 1">
				告诉您一个小秘密~最近{{recentDay}}天的平均体重您{{trend}}{{ absRecentWeight }}{{unitPound}}。
			</view>
			<view class="txt-container" v-if="recentDay == 1">
				再记1天体重我才告诉您小秘密~。
			</view>
			<view class="txt-container" v-if="recentDay == -1">
				再记2天体重我才告诉您小秘密~。
			</view>
		</view>
		<!-- 中间部分 -->
		<!-- 中间部分 -->
		<view class="center-container" id="ccImg">
			<!-- 图片 -->
			<image :src="backImgSrc" class="center-img" @load="loadImg()" mode="widthFix"></image>
			<view class="txt-btn-group">
				<!-- 文字部分 -->
				<view class="soup-txt">
					{{ soupTxt }}
				</view>
				<!-- 保存按钮 -->
				<view class="save-btn-group">
					<u-button class="save-btn" style="width: 300rpx;" shape="circle" size="large" @click="savePng"
						color="rgba(178, 89, 0, 0.5)">
						保存图文到相册
					</u-button>
				</view>
			</view>
			<!-- 底部二维码 -->
			<!-- <view class="bottom-qrcode"> -->
			<!-- 二维码图片 -->
			<!-- <image src="/static/gh_c3df6125b265_344.jpg"></image>
				<view class="bottom-txt">
					微信长按图片扫码看更多
				</view>
			</view> -->
		</view>
		<canvas canvas-id="myCanvas" id="myCanvas"
			:style="{width:width+'px',height:height+'px',top:'-9999px',position:'absolute'}"></canvas>
		<!-- 底部部分 -->
		<view class="bottom-container">
			<!-- 底部文字 -->
			<view class="bottom-txt">
				今天是铁蛋陪您的第{{totalDay}}天
			</view>
			<view class="bottom-txt">
				您共记录了{{ totalRecord}}天体重
			</view>
		</view>
		<!-- 画布 -->
		<!-- <poster config="" bind:success="onPosterSucces"></poster> -->
	</view>
</template>

<script>
	import {
		baseUrl,
		imgUrl
	} from "../../config/index.js";
	export default {
		data() {
			return {
				headImgSrc: "",
				backImgSrc: "",
				weightTxt: "",
				soupTxt: "人的举动都不是无端的做出。————西格蒙德·弗洛伊德",
				base64: null,
				recentDay: 0,
				recentWeight: 0,
				unit: 0,
				totalDay: 0,
				totalRecord: 0,
				saveBtnShow: false,
				bottomMoreShow: false,
				height: uni.getSystemInfoSync().height,
				width: uni.getSystemInfoSync().width,
				codeSrc: '/static/gh_c3df6125b265_344.jpg',
				templateImgFilePath: '',
				current: 0,
				hidepic: null,
				showpic: null
			}
		},
		methods: {
			// 删除记录体重文字
			generateWeightTxt() {
				this.weightTxt = "增加了XX斤"
			},
			// 获取网络图片临时地址
			getImgTempPath(e) {
				let self = this;
				uni.getImageInfo({
					src: self.backImgSrc,
					success: function(res) {
						console.log("tempImgFilePath", res)
						self.templateImgFilePath = res.path;
					},
					fail: function(err) {
						console.log(err)
					}
				})
			},
			savePng() {
				this.generatePoster();
				// 获取canvas地址保存图片
				uni.canvasToTempFilePath({
					canvasId: 'myCanvas',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(data) {
								wx.showToast({
									title: '保存到系统相册成功',
									icon: 'success',
									duration: 2000
								})
							},
							fail: function(err) {
								console.log(err);
								if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
									console.log("当初用户拒绝，再次发起授权")
									wx.openSetting({
										success(settingdata) {
											console.log(settingdata)
											if (settingdata.authSetting[
													'scope.writePhotosAlbum']) {
												console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
											} else {
												console.log('获取权限失败，给出不给权限就无法正常使用的提示')
											}
										}
									})
								} else {
									wx.showToast({
										title: '保存失败',
										icon: 'none'
									});
								}
							},
							complete(res) {
								console.log(res);
							}
						})
					}
				})
			},
			generatePoster() {
				// this.getImgTempPath(this.backImgSrc);
				// uni.showLoading({
				// 	title: '正在保存',
				// 	mask: true,
				// })
				var chr = this.soupTxt.split("");
				var temp = "";
				var row = [];
				let self = this;
				const ctx = uni.createCanvasContext('myCanvas');
				// 绘制背景图
				ctx.drawImage(self.templateImgFilePath, 0, 0, self.width, self.height);
				// 绘制图片二维码
				ctx.drawImage(this.codeSrc, ((this.width - 60) / 2) + 8, this.height - 120, 60, 60);
				ctx.setFontSize(22);
				// 计算文字
				for (var a = 0; a < chr.length; a++) {
					if (ctx.measureText(temp).width < (this.width - 55)) {
						temp += chr[a];
					} else {
						a--;
						row.push(temp);
						temp = "";
					}
				}
				row.push(temp);
				// 绘制遮罩层
				ctx.lineWidth = 12;
				ctx.setFillStyle('rgba(0,0,0,0.5)');
				ctx.setStrokeStyle('rgba(0,0,0,0.5)');
				ctx.strokeRect(0, this.height / 3);
				ctx.fillRect(0, this.height / 3, this.width, row.length * 43);
				// 绘制文字
				for (var b = 0; b < row.length; b++) {
					ctx.setFillStyle("#fff");
					ctx.fillText(row[b], 24, ((this.height / 3) + 40) + b * 34, (this.width - 55));
				}
				// 绘制底部文字
				ctx.setFontSize(14);
				ctx.setFillStyle("#fff");
				ctx.fillText("微信长按图片扫码看更多", (this.width - 140) / 2, this.height - 40, 200);
				ctx.draw(true);
			},
			base64ToBlob(urlData, type) {
				let arr = urlData.split(',')
				// let name = 'file'
				let mime = arr[0].match(/:(.*?);/)[1] || type
				// 去掉url的头,并转化为byte
				let bytes = window.atob(arr[1])
				// 处理异常,将ascii码小于0转为大于0
				let ab = new ArrayBuffer(bytes.length)
				// 生成试图(直接针对内存):8位无符号整数,长度1个字节
				let ia = new Uint8Array(ab)
				for (var i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i)
				}
				return new Blob([ab], {
					type: mime
					// name: name
				})
			},
			// 获取随机鸡汤文
			getRandomTheory() {
				let self = this;
				uni.request({
					url: baseUrl + '/getRandomTheory',
					method: 'get',
					success: function(res) {
						console.log(res)
						if (res.data.success) {
							self.soupTxt = res.data.data
						}
						self.saveBtnShow = true;
					}
				})
			},
			// 获取历史数据
			getHistoryDatum() {
				let self = this;
				uni.request({
					url: baseUrl + '/getHistoryDatum',
					data: {
						openid: uni.getStorageSync("openid")
					},
					method: 'post',
					header: {
						'Content-Type': 'application/json'
					},
					success: function(res) {
						let e = res.data.data;
						self.totalRecord = e.recordNumber;
						let oneDay = 24 * 60 * 60 * 1000;
						let startTime = new Date(e.registerTime);
						let endTime = new Date();
						self.totalDay = Math.round(Math.abs((startTime - endTime) / oneDay));
						console.log(res)
					}
				})
			},
			getRect() {
				var _this = this;
				//我这里需要获取多个元素的高度，所以用的是selectAll
				wx.createSelectorQuery().selectAll(
						'.center-container, .center-img, .soup-txt, .bottom-txt, .bottom-qrcode')
					.boundingClientRect()
					.exec(function(res) {
						console.log(res)
						_this.bgInfo = res[0][0];
						_this.masker = res[0][1];
						_this.txtInfo = res[0][2];
					})
			},
			// 处理加载成功后事件
			loadImg(e){
				uni.hideLoading();
			}
		},
		computed: {
			trend() {
				return this.recentWeight >= 0 ? '增加了' : '减少了';
			},
			unitPound() {
				return this.unit == 1 ? "公斤" : "斤";
			},
			absRecentWeight() {
				return Math.abs(this.recentWeight);
			}
		},
		onShow() {
			// 头部左侧图片索引
			const imageIndex = (Math.floor(Math.random() * 24) + 1).toString().padStart(3, '0');
			// 背景图片索引
			const backImageIndex = (Math.floor(Math.random() * 28) + 1).toString().padStart(3, '0');
			this.headImgSrc = `${imgUrl}/img/emoj/mm${imageIndex}.gif`;
			this.backImgSrc = `${imgUrl}/img/bg/${backImageIndex}.jpg`;
			this.getImgTempPath();
			console.log(this.backImgSrc)
			this.generateWeightTxt();
			this.getRandomTheory();
			this.getHistoryDatum()
			uni.showLoading({
				title:'加载中...',
				mask:true
			})
		},
		onLoad({
			recentDay,
			recentWeight,
			unit
		}) {
			let self = this;
			this.recentDay = recentDay;
			this.recentWeight = recentWeight;
			this.unit = unit;
			uni.getSystemInfo({
				success: function(res) {
					self.width = res.windowWidth;
					self.height = res.windowHeight * 0.8
				}
			})
		},
		mounted() {}
	}
</script>

<style lang="scss" scoped>
	.head-container {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		font-size: 20px;
		margin-top: 40rpx;
		margin-right: 20rpx;

		.image-container {
			flex-grow: 3;

			.head-img {
				height: 160rpx;
				width: 160rpx;
				margin-left: 40rpx;
			}
		}

		.txt-container {
			font-size: 20px;
			margin-left: 40rpx;
			flex-grow: 1;
		}

		// .head-img {
		// 	height: 600rpx;
		// 	width: 200rpx;
		// 	margin-left: 40rpx;
		// }
	}

	.center-container {
		position: relative;
		width: 100%;
		height: 1080rpx;
		margin-top: 20rpx;
		overflow: hidden;

		.center-img {
			width: 100%;
			z-index: 1;
			animation: fadein 3s;
		}

		@keyframes fadein {
			0% {
				opacity: 0.1;
			}

			100% {
				opacity: 1;
			}

		}


		.txt-btn-group {
			top: 50%;
			position: absolute;
			width: 100%;
			height: auto;
			transform: translate(0, -50%);
			-webkit-transform: translate(0, -50%);

			& .soup-txt {
				text-align: left;
				font-size: 22px;
				padding: 40rpx 40rpx;
				line-height: 60rpx;
				color: white;
				height: auto;
				background-color: rgba(0, 0, 0, 0.5);
				margin-bottom: 40rpx;
			}

			& .save-btn-group {
				width: fit-content !important;
				margin: auto;
				font-size: 22px;

				& .save-btn {
					// background-color: rgba(178, 89, 0, 0.5);
					color: white;
					font-weight: bold;
					text-align: center;
					border: none;
				}
			}
		}

		.bottom-qrcode {
			position: absolute;
			top: 70%;
			left: 50%;
			-webkit-transform: translate(-50%, 150%);
			transform: translate(-50%, 150%);
			z-index: 999;
			text-align: center;

			& image {
				width: 70rpx;
				height: 70rpx;
			}

			.bottom-txt {
				font-size: 12px;
				color: #fff;
			}
		}
	}

	.bottom-container {
		padding: 28rpx 0 28rpx 40rpx;
		color: #8d8b86;
	}
</style>